<template>
  <div class="theme-content-item" style="position: relative;height: 100vh;overflow: auto">
    <div class="padding-20px">
      <div class="left-title">{{ title }}</div>
      <el-form ref="formRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="销售姓名" prop="saleName">
              <el-input v-model="form.saleName" placeholder="请输入销售姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="是否企业订单" prop="isEnt">
              <el-checkbox v-model="form.isEnt"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="10" >
            <el-form-item label="支付方式" prop="payType">
              <el-select clearable v-model="form.payType" placeholder="请选择支付方式">
                <el-option v-for="item in $Const.payTypeList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="付款人" prop="payUserName">
              <el-input v-model="form.payUserName" placeholder="请输入付款人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="付款金额" prop="payPrice">
              <el-input type="number" v-model="form.payPrice" placeholder="请输入付款金额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="付款日期" prop="payTime">
              <el-date-picker
                  v-model="form.payTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="data"
                  placeholder="请选择付款日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="说明" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入说明" maxlength="100" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="padding: 15px 20px">
        <div class="left-title">商品列表</div>

        <div v-if="isAdd" class="flex-jc-s-b">
          <el-button style="margin-top: 20px" @click="showDialog()">新增商品</el-button>
        </div>

        <el-table
            :data="form.itemList"
            row-key="id"
        >
          <el-table-column prop="goodsName" label="商品名称" >
            <template #default="scope">
              <span>{{ scope.row.goodsName + '-' + scope.row.goodsSkuName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="originPrice" label="原价" >
          </el-table-column>
          <el-table-column prop="payPrice" label="现价" />
          <el-table-column prop="buyerName" label="用户姓名" />
          <el-table-column prop="buyerMobile" label="手机号" />
          <el-table-column label="操作" >
            <template v-if="isAdd" #default="scope" >
              <el-button plain type="primary" @click="showDialog(scope.row, true, scope.$index)">修改</el-button>
              <el-button type="danger" plain @click="deleteItem(scope.row.index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="height: 200px"></div>

      <form-dialog v-model="dialogVisible" :title="data.dialogTitle" @save="saveItem()">
        <el-form :rules="itemRules" :model="data.itemForm" label-width="120px" style="width: 100%">
          <el-form-item label="商品" prop="goodsSkuId">
            <el-cascader v-model="data.itemForm.goodsSkuId" placeholder="请选择商品" :options="data.goodsList"
                         :props="{label:'name',value:'id',children:'skuList',emitPath:false}" @change="changeGoodsSku"/>
          </el-form-item>
          <el-form-item label="原价" prop="originPrice">
            <el-input  v-model="data.itemForm.originPrice" disabled style="width: 50%"/>
          </el-form-item>
          <el-form-item label="现价" prop="payPrice">
            <el-input type="number" v-model="data.itemForm.payPrice" placeholder="请输入现价" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="用户姓名" prop="buyerName">
            <el-input v-model="data.itemForm.buyerName" placeholder="请输入用户姓名" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="手机号" prop="buyerMobile">
            <el-input v-model="data.itemForm.buyerMobile" placeholder="请输入手机号" style="width: 50%"/>
          </el-form-item>
        </el-form>
      </form-dialog>

      <div style=" position: fixed; bottom: 5%; left: 45%;z-index: 99" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from "element-plus";
import useEditor from "../../../common/component/rich/editor"
import {addOrder, editOrder, getOrderDetail} from "../../../../api/order";
import {listGoods} from "../../../../api/goods";

const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('')
const isAdd = ref(true)
const dialogVisible = ref(false)

const { toolbarConfig, editorConfig, editorData, handleCreated, destroyEditor } = useEditor()

const data = reactive({
  dialogTitle: '保存商品',
  goodsList: [],
  itemForm: {},
  lastEditIndex: -1
})

const form = reactive({
  id: null,
  saleName: '',
  isEnt: false,
  payType: '',
  payUserName: '',
  payPrice: '',
  payTime: '',
  remark: '',
  itemList: []
})

const rules = ({
  saleName: [{ required: true, message: '请输入销售姓名', trigger: 'blur' }],
  payType: [{ required: true, message: '请选择支付类型', trigger: 'blur' }],
  payUserName: [{ required: true, message: '请输入付款人', trigger: 'blur' }],
  payPrice: [{ required: true, message: '请输入付款金额', trigger: 'blur' }],
  payTime: [{ required: true, message: '请选择付款日期', trigger: 'blur' }]
})

// 详情
const initDetail = () => {
  getOrderDetail(route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => { form[`${key}`] = resData[`${key}`] })
    form.isEnt = resData.enterpriseFlag == 1
  })
}
const initData = () => {
  let req = {publishedFlag : 1, showSkuFlag: 1, showTeacherFlag: 0}
  listGoods(req).then((res)=>{
    data.goodsList = res.rows
  })
}

const save = () => {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      let requestData = {}
      Object.keys(form).forEach((key) => { requestData[`${key}`] = form[`${key}`] })

      requestData.enterpriseFlag = form.isEnt ? 1 : 0
      if (isAdd.value) {
        addOrder(requestData).then((res) => {
          reset()
          ElMessage.success('操作成功');
        })
      }else{
        requestData.itemList = null
        editOrder(requestData).then((res)=>{
          ElMessage.success('操作成功');
        })
      }
    }
  })
}

const reset = () => {
  let requestData = {
    id: null,
    saleName: '',
    isEnt: false,
    payType: '',
    payUserName: '',
    payPrice: '',
    payTime: '',
    remark: '',
    itemList: []
  }
  Object.keys(requestData).forEach((key) => { form[`${key}`] = requestData[`${key}`] })
}

const changeGoodsSku = (goodsSkuId) => {
  // id冲突
  // let goodsSkuItem = getTreeItemById(data.goodsList, goodsSkuId, 'skuList')
  let skuItem = getStuItemId(goodsSkuId)
  data.itemForm.originPrice = skuItem.realPrice
}
const getStuItemId = (goodsSkuId) => {
  for (let i = 0; i < data.goodsList.length; i++) {
    let sku = data.goodsList[i].skuList.find(skuItem => skuItem.id == goodsSkuId)
    if (sku) return sku
  }
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  let type = routeQuery.type
  let titleValue = '新增'
  if (type) {
    titleValue = titleMap[routeQuery.type]
  }
  title.value = titleValue
  isAdd.value = routeQuery.type != 'edit'
  if (!isAdd.value) {
    initDetail()
  }

  initData()
})

const itemRules = ({
  goodsSkuId: [{ required: true, message: '请选择商品', trigger: 'blur' }],
  payPrice: [{ required: true, message: '请输入付款金额', trigger: 'blur' }],
  buyerName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  buyerMobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
})

const showDialog = (targetItem, isEdit, editIndex) => {
  dialogVisible.value = true
  if (isEdit){
    Object.assign(data.itemForm, targetItem)
    data.lastEditIndex = editIndex
  }else{
    data.itemForm = {}
  }
  data.itemForm.isEdit = isEdit
}

const saveItem = () => {
  let item = data.itemForm

  let newItem = {}
  Object.assign(newItem, item)
  let goodsSkuId = data.itemForm.goodsSkuId
  // let goodsSkuItem = getTreeItemById(data.goodsList, goodsSkuId, 'skuList')
  let goodsSkuItem = getStuItemId(goodsSkuId)
  let goodsId = goodsSkuItem.goodsId
  if (!goodsId) {
    return ElMessage.warning('请选择商品sku')
  }
  let goodsItem = data.goodsList.find(item => item.id == goodsId)

  newItem.goodsName = goodsItem.name
  newItem.goodsSkuName = goodsSkuItem.name
  if (item.isEdit) {
    let targetItem = form.itemList[data.lastEditIndex]
    Object.assign(targetItem, newItem)
  } else {
    form.itemList.push(newItem)
  }
  dialogVisible.value = false
}

const deleteItem = (index) => {
  proxy.$modal.confirm("确定删除该数据？").then(() => {
    let list = form.itemList
    list.splice(index, 1)
  })
}

</script>
<style scoped lang="scss">
:deep(.el-input) {
  width: 400px;
}
:deep(.el-input__wrapper) {
  width: 400px;
}
</style>
